# coding=utf-8
import urllib

from middlewares.middleware import Middleware


class ProxyScraperApiMiddleware(Middleware):
    def __init__(self):
        super(ProxyScraperApiMiddleware, self).__init__(self._inner_process)

    def _inner_process(self, request):
        if "http://api.scraperapi.com" in request.url:
            return request.url
        else:
            request.url = self.scraperapi_url2(request.url)

    def scraperapi_url2(self, url):
        encoded_url = urllib.urlencode({"url": url})
        scarper_url = "http://api.scraperapi.com?key=21e40228e971e1dc070d20a2f456e82a&"+encoded_url+"&keep_headers=true"
        return scarper_url

    # def scraperapi_url(self, url):
    #     url = url.replace(':', '%3A')
    #     url = url.replace('/', '%2F')
    #     url = url.replace('+', '%2B')
    #     url = url.replace(' ', '%20')
    #     url = url.replace('?', '%3F')
    #     # url = url.replace('%', '%25')
    #     url = url.replace('#', '%23')
    #     url = url.replace('&', '%26')
    #     url = url.replace('=', '%3D')
    #     scarper_url = 'http://api.scraperapi.com?key=21e40228e971e1dc070d20a2f456e82a&url=' + url + '&keep_headers=true'
    #     # log_info(scarper_url)
    #     return scarper_url